package com.jjshop.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.jjshop.R;
import com.jjshop.dialog.JJmailImageSaveDialog;
import com.jjshop.dialog.JJmailImageShareDialog;
import com.jjshop.utils.DeviceUtils;
import com.jjshop.utils.GlobalContanst;
import com.jjshop.utils.JsonUtils;
import com.jjshop.utils.LogUtil;
import com.jjshop.utils.PreUtils;
import com.jjshop.utils.ShareUtils;
import com.jjshop.utils.StringUtil;
import com.jjshop.utils.Tools;
import com.jjshop.widget.X5WebView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends BaseActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private ImmersionBar mImmersionBar;

    private ProgressBar mProgressBar;
    private X5WebView mWebView;

    private String urlStr;
    private String webUrl = "https://yxds.999d.com/m/index/index?shop=537fdt";
    /**
     * 微信支付结果的url
     */
    private String payResultUrl;

    private String mWebTitle, webThumb, webIntro;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.fitsSystemWindows(true)
                .statusBarColor(android.R.color.white)
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(android.R.color.black).init();

        mWebView = findViewById(R.id.webview);
        mProgressBar = findViewById(R.id.progressBar);
        if(Build.VERSION.SDK_INT>=23){
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.SET_DEBUG_APP,Manifest.permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS,Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this,mPermissionList,123);
        }
    }

    /*
	 * call javascript
	 */
    public void runJs(String method, String... params) {
        StringBuffer jsBuffer = new StringBuffer();
        jsBuffer.append("javascript:");
        jsBuffer.append(method);
        jsBuffer.append("(");
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                if (i == 0) {
                    jsBuffer.append("'" + params[i] + "'");
                } else {
                    jsBuffer.append(",'" + params[i] + "'");
                }
            }
        }
        jsBuffer.append(")");
        mWebView.loadUrl(jsBuffer.toString());
    }


    @Override
    protected void setListener() {

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                mProgressBar.setProgress(0);
                mProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                mProgressBar.setVisibility(View.INVISIBLE);
//                writeData();
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {

            }

            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int progress) {
                mProgressBar.setProgress(progress);
                if (progress == 100) {
                    mProgressBar.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void initData() {

        //刷新设备信息
        String device = "device=#" + StringUtil.textToMD5L32(DeviceUtils.getDeviceCode(this)) + "#Android#" + android.os.Build.VERSION.RELEASE + "#JJdance#" + StringUtil.getAppVersionName(this) + "#" + android.os.Build.MODEL + "#null#" + DeviceUtils.getOperators(this) +
                "#" + DeviceUtils.getNetworkType(this) + "#" + DeviceUtils.getesolution(this)[0] + "#" + DeviceUtils.getesolution(this)[1] + "#" + DeviceUtils.getWindowSize(this)[1] + "#" + DeviceUtils.getWindowSize(this)[0] + "#" +
                PreUtils.getFloat(this, PreUtils.LATITUDE, 0) + "#" + PreUtils.getFloat(this, PreUtils.LONTITUDE, 0) + "#;";
        PreUtils.setString(this, PreUtils.DEVICE, device);
        urlStr = StringUtil.transEndoing(this, PreUtils.getString(this, PreUtils.UAUTH, ""));

        mWebView.addJavascriptInterface(this, "gcw");
        String ua = mWebView.getSettings().getUserAgentString();
        mWebView.getSettings().setUserAgentString(ua + " YT-Android/" + StringUtil.getAppVersionName(this) + " YT-LOGIN-TOKEN:" + urlStr +"99yanxuanapp");
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
//        CookieManager.getInstance().setCookie(webUrl, "_uauth=" + PreUtils.getString(this, PreUtils.UAUTH, ""));
//        CookieManager.getInstance().setCookie(webUrl, PreUtils.getString(this, PreUtils.USER_ID, ""));
//        CookieManager.getInstance().setCookie(webUrl, PreUtils.getString(this, PreUtils.USER_AUTH, ""));
//        CookieManager.getInstance().setCookie(webUrl, PreUtils.getString(this, PreUtils.USER_MOBILE, ""));
//        CookieManager.getInstance().setCookie(webUrl, PreUtils.getString(this, PreUtils.DEVICE, ""));

        mWebView.loadUrl(webUrl);

        regReceiver();
    }

    /**
     * 注册监听微信支付结果的广播
     */
    private void regReceiver() {
        IntentFilter filter = new IntentFilter(GlobalContanst.ACTION_PAY_RESULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(mPayResultReceiver, filter);
    }

    /**
     * 注销监听微信支付结果的广播
     */
    private void unRegReceiver() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mPayResultReceiver);
    }

    private BroadcastReceiver mPayResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("test", "pay url=" + payResultUrl);
            if (!TextUtils.isEmpty(payResultUrl)) {
                mWebView.loadUrl(payResultUrl);
            }
        }
    };

    /**
     * 退出web
     */
    @JavascriptInterface
    public void popToRoot(){
        finish();
    }

    /**
     * 微信支付
     */
    @JavascriptInterface
    public void call_weixin_app_pay(String json) {
        /*Log.d("run...", "thread name="+Thread.currentThread().getName());
        Log.d("run..", "json=" + json);*/
        IWXAPI api = WXAPIFactory.createWXAPI(this, GlobalContanst.WECHAT_APP_ID);
        api.registerApp(GlobalContanst.WECHAT_APP_ID);
        try {
            JSONObject jsonObject = new JSONObject(json);
            payResultUrl = jsonObject.getString("pay_result_url");
            PayReq req = new PayReq();
            req.appId = jsonObject.getString("appid");
            req.partnerId = jsonObject.getString("partnerid");
            req.prepayId = jsonObject.getString("prepayid");
            req.nonceStr = jsonObject.getString("noncestr");
            req.timeStamp = jsonObject.getString("timestamp");
            req.packageValue = jsonObject.getString("package");
            req.sign = jsonObject.getString("sign");
            req.extData = "app data"; // optional
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 邀请开店
     *
     * @param json
     */
    @JavascriptInterface
    public void share(String json) {
        try {
            ArrayList<Map<String, String>> listMapByJson = JsonUtils.getListMapByJson(json);
            if (listMapByJson.size() <= 0) {
                return;
            }
            Map<String, String> map = listMapByJson.get(0);
            final String title = map.get("title");
            final String intro = map.get("intro");
            final String thumb = map.get("thumb");
            final String url = map.get("url");
            String qrcodeimg = map.get("qrcodeimg");
            String status = map.get("status");
            mWebTitle = title;
            webUrl = url;
            webThumb = thumb;
            webIntro = intro;

            //            if ("1".equals(status)) {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ShareUtils.shareWeb(MainActivity.this, title, intro, thumb, url,

                            new UMShareListener() {
                                @Override
                                public void onStart(SHARE_MEDIA share_media) {

                                }

                                @Override
                                public void onResult(SHARE_MEDIA share_media) {
                                    //                                        String url = "javascript:shareComplete('success')";
                                    //                                        webView.loadUrl(url);

                                    int type = ShareUtils.getType(share_media);
                                    String url = "javascript:shareComplete('success','" + type + "')";
                                    mWebView.loadUrl(url);
                                }

                                @Override
                                public void onError(SHARE_MEDIA share_media, Throwable throwable) {

                                }

                                @Override
                                public void onCancel(SHARE_MEDIA share_media) {

                                }
                            });
                }
            });
            //            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 这个方法在网页一打开的时候就会被调用以便于获取到要分享的数据信息，现在加了status
     * 用于判断是否要显示分享面板。\
     * <p>
     * 商品店铺分享 商品分享
     *
     * @param json
     */
    @JavascriptInterface
    public void productShopShare(String json) {
        //        if (timer != null ){
        //            timer.cancel();
        //            timer = null;
        //        }
        LogUtil.e("shareData:" + json);
        //        String mWebTitle,webUrl, urlStr, webThumb, webIntro;
        try {
            ArrayList<Map<String, String>> listMapByJson = JsonUtils.getListMapByJson(json);
            if (listMapByJson.size() <= 0) {
                return;
            }
            Map<String, String> map = listMapByJson.get(0);
            final String title = map.get("title");
            final String intro = map.get("intro");
            final String thumb = map.get("thumb");
            final String url = map.get("url");
            final String qrcodeimg = map.get("qrcodeimg");
            final String shareImgs = map.get("share_imgs");
            //            String status = map.get("status");
            mWebTitle = title;
            webUrl = url;
            webThumb = thumb;
            webIntro = intro;

            //            if ("1".equals(status)) {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    share(title, intro, thumb, url, qrcodeimg,shareImgs, true);
                }
            });
            //            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //        webShare.setEnabled(true);
    }

    /**
     * 分享，没有二维码
     *
     * @param json
     */
    @JavascriptInterface
    public void productShopShareNoImg(String json) {
        try {
            ArrayList<Map<String, String>> listMapByJson = JsonUtils.getListMapByJson(json);
            if (listMapByJson.size() <= 0) {
                return;
            }
            Map<String, String> map = listMapByJson.get(0);
            final String title = map.get("title");
            final String intro = map.get("intro");
            final String thumb = map.get("thumb");
            final String url = map.get("url");
            final String qrcodeimg = map.get("qrcodeimg");
            final String shareImgs = map.get("share_imgs");
            //            String status = map.get("status");
            mWebTitle = title;
            webUrl = url;
            webThumb = thumb;
            webIntro = intro;

            //            if ("1".equals(status)) {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    share(title, intro, thumb, url, qrcodeimg,shareImgs, false);
                }
            });
            //            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void share(final String title, String intro, String thumb, final String url, final String qrcodeimg,
                       String shareImgs, boolean isHaveImg) {
        ArrayList<Map<String, String>> listMapByJson = JsonUtils.getListMapByJson(shareImgs);
        if (listMapByJson.size()==0){
            shareImgs = "";
        }
        final String finalShareImgs = shareImgs;
        if (thumb.contains("?")){
            thumb = thumb.substring(0,thumb.indexOf("?"));
        }
        ShareUtils.shareJJmailProductShop(MainActivity.this, title, intro, thumb, url,shareImgs, isHaveImg, new ShareUtils.OnJJMailCallBack() {

                    @Override
                    public void onSave() {
                        JJmailImageSaveDialog dialog = new JJmailImageSaveDialog();
                        Bundle bundle = new Bundle();
                        bundle.putString("img", qrcodeimg);
                        dialog.setArguments(bundle);
                        dialog.setOnSaveImgListener(new JJmailImageSaveDialog.OnSaveImgListener() {
                            @Override
                            public void save() {
                                saveImgCheckPermission(qrcodeimg);
                            }
                        });
                        dialog.show(getSupportFragmentManager(), "JJmailImageSaveDialog");
                        //                        saveImg(qrcodeimg);
                    }

                    @Override
                    public void onMoreImg() {
                        shareImage(1, finalShareImgs,title,url);
                    }

                    @Override
                    public void onCopy() {
                        //复制链接
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        // 将文本内容放到系统剪贴板里。
                        cm.setText(url);
                        Toast.makeText(MainActivity.this, "复制成功", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onCallBack() {
                        JJmailImageShareDialog dialog = new JJmailImageShareDialog();
                        Bundle bundle = new Bundle();
                        bundle.putString("img", qrcodeimg);
                        dialog.setArguments(bundle);
                        dialog.setOnJJmailShareClickListener(new JJmailImageShareDialog.OnJJmailShareClickListener() {
                            @Override
                            public void left() {
                                UMImage image = new UMImage(MainActivity.this, qrcodeimg);//网络图片
                                new ShareAction(MainActivity.this)
                                        .setPlatform(SHARE_MEDIA.WEIXIN)
                                        .withMedia(image)
                                        .share();
                            }

                            @Override
                            public void right() {
                                UMImage image = new UMImage(MainActivity.this, qrcodeimg);//网络图片
                                new ShareAction(MainActivity.this)
                                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                        .withMedia(image)
                                        .share();
                            }
                        });
                        dialog.show(getSupportFragmentManager(), "JJmailImageShareDialog");
                    }
                },
                new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        //                                        String url = "javascript:shareComplete('success')";
                        //                                        webView.loadUrl(url);

                        int type = ShareUtils.getType(share_media);
                        String urls = "javascript:shareMailComplete('success','" + type + "','" + url + "')";
                        mWebView.loadUrl(urls);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
//                        window.shareError = function(response, code, resurl)
                        int type = ShareUtils.getType(share_media);
                        runJs("shareError",new String[]{"error",""+type,"0"});
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {

                    }
                });
    }

//    private void writeData() {
//        String key = "token";
//        String val = "";//SpfsUtils.readString(MyApp.getContext(),"token");
//        String key2 = "is_app";
//        String val2 = "101";
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
//            mWebView.evaluateJavascript("window.localStorage.setItem('" + key + "','" + val + "');", null);
//            mWebView.evaluateJavascript("window.localStorage.setItem('" + key2 + "','" + val2 + "');", null);
//        } else {
//            mWebView.loadUrl("javascript:localStorage.setItem('" + key + "','" + val + "');");
//            mWebView.loadUrl("javascript:localStorage.setItem('" + key2 + "','" + val2 + "');");
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, intent);
    }


    private long startTime;

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.loadUrl("javascript:history.go(-1)");
            return;
        }
        long endTime = System.currentTimeMillis();
        if (endTime - startTime < 2000) {
            super.onBackPressed();
        } else {
            startTime = endTime;

            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
        }

    }

//    @Override
//    public void onBackPressed() {
//        //super.onBackPressed();
//        if (mWebView!=null){
//            mWebView.loadUrl("javascript:history.go(-1)");
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        unRegReceiver();
    }

    private ProgressDialog progressDialog;
    private void showProgress(String massage){
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        if (TextUtils.isEmpty(massage)) {
            progressDialog.setMessage("正在获取二维码...");
        }else{
            progressDialog.setMessage(massage);
        }
        progressDialog.show();
    }

    private void hideProgress(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.cancel();
            }
        }
    }

    public static final String[] permissions_required = new String[]{"android.permission.READ_PHONE_STATE", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.ACCESS_WIFI_STATE", "android.permission.ACCESS_NETWORK_STATE"};
    private String mImg = "";
    private void saveImgCheckPermission(String img){
        mImg = img;

        if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                ) {
//            ActivityCompat.shouldShowRequestPermissionRationale(this,PackageManager.)

            ActivityCompat.requestPermissions(this, permissions_required, 1);
        }else {
            saveImg(img);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != 123){
            if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                    ){
                saveImg(mImg);
            }else{

            }
        }
//        if(BaseAD.hasPermission(this)){

    }

    private void saveImg(String downloadPath){
        showProgress("正在保存二维码");
        HttpUtils utils = new HttpUtils();
        if (downloadPath.contains("?")){
            downloadPath = downloadPath.substring(0,downloadPath.indexOf("?"));
        }
//        final String fileName = System.currentTimeMillis() + "jj.png";
        final String fileName = downloadPath.substring(downloadPath.lastIndexOf("/")+1);
        final int type = fileName.contains(".png") || fileName.contains(".PNG")  ? 0 : 1;
        String absolutePath = getExternalStorageDirectory()
                .getAbsolutePath() + "/jjdance/download/jjdance/";// /mnt/sdcard
        final String apkPath = absolutePath + fileName;
        final HttpHandler handler = utils.download(downloadPath, apkPath,
                false, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        StringUtil.showToast(MainActivity.this, "已保存到相册");
//                        try {
//                            MediaStore.Images.Media.insertImage(QualificationSaveMaActivity.this.getContentResolver(), apkPath, fileName, null);
//                            QualificationSaveMaActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(apkPath))));
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        }
                        saveImageToGallery(MainActivity.this, BitmapFactory.decodeFile(apkPath),type);



//                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//                        Uri uri = Uri.parse(apkPath);
//                        intent.setData(uri);
//                        QualificationSaveMaActivity.this.sendBroadcast(intent);

//                        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
//                        scanIntent.setData(Uri.fromFile(new File(filePath)));
//                        context.sendBroadcast(scanIntent);


                        // 其次把文件插入到系统图库
//                        try {
//                            MediaStore.Images.Media.insertImage(QualificationSaveMaActivity.this.getContentResolver(),
//                                    apkPath, fileName, null);
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        }
//                        // 最后通知图库更新
//                        QualificationSaveMaActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + apkPath)));





//                        Context context = params[0].context;
//                        Bitmap image = params[0].image;
//                        Resources r = context.getResources();

//                        try {
//                            // Create screenshot directory if it doesn't exist
//                            mScreenshotDir.mkdirs();
//
//                            // media provider uses seconds for DATE_MODIFIED and DATE_ADDED, but milliseconds
//                            // for DATE_TAKEN
//                            long dateSeconds = mImageTime / 1000;
//
//                            // Save the screenshot to the MediaStore
//                            ContentValues values = new ContentValues();
//                            ContentResolver resolver = context.getContentResolver();
//                            values.put(MediaStore.Images.ImageColumns.DATA, mImageFilePath);
//                            values.put(MediaStore.Images.ImageColumns.TITLE, mImageFileName);
//                            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, mImageFileName);
//                            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, mImageTime);
//                            values.put(MediaStore.Images.ImageColumns.DATE_ADDED, dateSeconds);
//                            values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, dateSeconds);
//                            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/png");
//                            values.put(MediaStore.Images.ImageColumns.WIDTH, mImageWidth);
//                            values.put(MediaStore.Images.ImageColumns.HEIGHT, mImageHeight);
//                            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//
//                            OutputStream out = resolver.openOutputStream(uri);
//                            image.compress(Bitmap.CompressFormat.PNG, 100, out);
//                            out.flush();
//                            out.close();
//
//                            // update file size in the database
//                            values.clear();
//                            values.put(MediaStore.Images.ImageColumns.SIZE, new File(mImageFilePath).length());
//                            resolver.update(uri, values, null, null);
//
//
//                        } catch (Exception e) {
//
//                        }

//                        saveCallBack();
                        hideProgress();
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        StringUtil.showToast(MainActivity.this, "保存失败");
                        hideProgress();
                    }
                });
    }

    /**
     *
     * @param context
     * @param bitmap
     * @param type 0 png 1 jpeg
     */
    private void saveImageToGallery(Context context, Bitmap bitmap ,int type) {
        // Create screenshot directory if it doesn't exist
        String dirName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "MImages";
        File fileDir = new File(dirName);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        long mImageTime = System.currentTimeMillis();//取当前系统时间
        // media provider uses seconds for DATE_MODIFIED and DATE_ADDED, but milliseconds
        // for DATE_TAKEN
        long dateSeconds = mImageTime / 1000;
        String mImageFileName = dateSeconds + (type == 1?".jpeg": ".png"); //以保存时间命名
        String mImageFilePath = dirName + File.separator + mImageFileName; //注意这里的mImageFilePath是： 目录名称+文件名
        int mImageWidth = bitmap.getWidth();
        int mImageHeight = bitmap.getHeight();

        // Save the screenshot to the MediaStore
        ContentValues values = new ContentValues();
        ContentResolver resolver = context.getContentResolver();
        values.put(MediaStore.Images.ImageColumns.DATA, mImageFilePath);
        values.put(MediaStore.Images.ImageColumns.TITLE, mImageFileName);
        values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, mImageFileName);
        values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, mImageTime);
        values.put(MediaStore.Images.ImageColumns.DATE_ADDED, dateSeconds);
        values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, dateSeconds);
        values.put(MediaStore.Images.ImageColumns.MIME_TYPE, (type == 1? "image/jpeg" : "image/png"));
        values.put(MediaStore.Images.ImageColumns.WIDTH, mImageWidth);
        values.put(MediaStore.Images.ImageColumns.HEIGHT, mImageHeight);
        Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        try {
            OutputStream out = resolver.openOutputStream(uri);
            bitmap.compress((type == 0?Bitmap.CompressFormat.PNG:Bitmap.CompressFormat.JPEG), 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // update file size in the database
        values.clear();
        values.put(MediaStore.Images.ImageColumns.SIZE, new File(mImageFilePath).length());
        resolver.update(uri, values, null, null);
    }

    private List<File> files = new ArrayList<>();

    /**
     *
     * @param flag  0分享给微信好友  1分享到朋友圈
     */
    private void shareImage(final int flag, final String shareImgs, final String title, final String url) {

        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        if (!Tools.isWeixinAvilible(this)){
            Toast.makeText(MainActivity.this, "您还没有安装微信", Toast.LENGTH_SHORT).show();

        }else{
            showProgress("加载数据中");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //这一步一定要clear,不然分享了朋友圈马上分享好友图片就会翻倍
                    files.clear();

                    try {
                        ArrayList<Map<String, String>> listMapByJson = JsonUtils.getListMapByJson(shareImgs);
                        for (int i = 0; i < listMapByJson.size(); i++) {
                            File file = Tools.saveImageToSdCard(MainActivity.this, listMapByJson.get(i).get(""));
                            if (file != null) {
                                files.add(file);
                            }
                        }

                        Intent intent = new Intent();
                        ComponentName comp;

                        if (flag == 0) {
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                        } else {
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                            intent.putExtra("Kdescription", title+"\n"+url);
                            //复制链接
                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                            // 将文本内容放到系统剪贴板里。
                            cm.setText(title+"\n"+url);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "复制成功", Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        intent.setComponent(comp);
                        intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                        intent.setType("image/*");


                        ArrayList<Uri> imageUris = new ArrayList<Uri>();
                        for (File f : files) {
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                                Uri uri = FileProvider.getUriForFile(MainActivity.this,"com.jjshop.fileprovider", f);
//                                imageUris.add(uri);
//                            }else {
                                imageUris.add(Uri.fromFile(f));
//                            }

                        }
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                        startActivity(Intent.createChooser(intent,""));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                hideProgress();
                            }
                        });
                    }catch (Exception e){
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                hideProgress();
                            }
                        });
                    }
                }
            }).start();

        }


    }



}